<?php

/**
 * @Author: Wang Chunsheng 2192138785@qq.com
 * @Date:   2020-03-12 04:22:42
 * @Last Modified by:   Wang chunsheng  email:2192138785@qq.com
 * @Last Modified time: 2020-06-02 10:17:19
 */

namespace common\addons\diandi_shop\services;

use common\addons\diandi_shop\models\DdDiandiShopCart;
use common\addons\diandi_shop\models\DdGoods;
use common\addons\diandi_shop\models\DdGoodsSpec;
use common\addons\diandi_shop\models\DdSpecValue;
use Yii;
use common\services\BaseService;
use common\helpers\ErrorsHelper;
use common\helpers\ImageHelper;
use common\helpers\ResultHelper;
use common\helpers\StringHelper;

/**
 * Class SmsService.
 *
 * @author chunchun <2192138785@qq.com>
 */
class CartService extends BaseService
{
    public static function confirm($user_id, $goods_id, $num, $spec_id = 0)
    {
        $where = [
            'user_id' => $user_id, 'goods_id' => $goods_id,
        ];

        if ($spec_id) {
            $where['spec_id'] = $spec_id;
        }

        $isHave = DdDiandiShopCart::findOne($where);
        $spec_value_ids = explode('_', $spec_id);
        $specVal = DdSpecValue::find()
            ->where(['spec_value_id' => $spec_value_ids])
            ->indexBy('spec_value_id')
            ->all();
        $specs = [];
        if (!empty($spec_value_ids)) {
            foreach ($spec_value_ids as $key => $item) {
                $ks[] = $specVal[$item]['spec_value'];
            }
            $newKey = implode('_', $ks);
            $specs[$spec_id] = $newKey;
        }
        $goods = DdGoods::find()->where(['goods_id' => $goods_id])->one();

        // 校验库存
        if ($goods['stock'] < $num) {
            return ResultHelper::json(401, $goods['goods_name'].'库存不足', []);
        }

        if (!empty($isHave)) {
            if ($num < 0) {
                return ResultHelper::json(401, '商品数量不能为负数', []);
            } elseif ($num == 0) {
                DdDiandiShopCart::deleteAll($where);
            }

            $goods_price = $goods['goods_price'];

            if (!empty($spec_id)) {
                $spec = DdGoodsSpec::find()->where([
                    'goods_id' => $goods_id,
                    'spec_sku_id' => $spec_id,
                    ])->select(['goods_price', 'line_price'])->one();
                $goods_price = $spec['goods_price'];
            }

            $total_price = $num * $goods_price;

            DdDiandiShopCart::updateAll(['number' => $num,
                'total_price' => $total_price,
                'goods_price' => $goods_price,
                'line_price' => empty($spec_id) ? $goods['line_price'] : $spec['line_price'],
            ], $where);
        } else {
            $goods_price = $goods['goods_price'];

            if (!empty($spec_id)) {
                $spec = DdGoodsSpec::find()->where([
                    'goods_id' => $goods_id,
                    'spec_sku_id' => $spec_id,
                    ])->select(['goods_price', 'line_price'])->one();
                $goods_price = $spec['goods_price'];
            }

            $total_price = $num * $goods_price;
            $DdDiandiShopCart = new DdDiandiShopCart();
            $datas = [
                'user_id' => $user_id,
                'goods_id' => $goods_id,
                'number' => $num,
                'line_price' => empty($spec_id) ? $goods['line_price'] : $spec['line_price'],
                'goods_price' => $goods_price,
                'total_price' => $total_price,
                'spec_id' => $spec_id,
                'spec_val' => $specs[$spec_id],
                'create_time' => time(),
            ];
            if (!$DdDiandiShopCart->load($datas, '') || !$DdDiandiShopCart->save()) {
                return ErrorsHelper::getModelError($DdDiandiShopCart);
            }
        }

        return self::list($user_id);
    }

    public static function list($user_id, $ids = [])
    {
        $lists = [];
        $goods_num = [];

        $bloc_id = Yii::$app->params['bloc_id'];
        $store_id = Yii::$app->params['store_id'];
        $where = [];
        $where['user_id'] = $user_id;
        if ($bloc_id) {
            $where['bloc_id'] = $bloc_id;
        }

        if ($store_id) {
            $where['store_id'] = $store_id;
        }

        if ($ids) {
            $where['id'] = $ids;
        }

        $list = DdDiandiShopCart::find()
            ->where($where)
            ->with(['goods', 'goodsSpec'])
            ->asArray()
            ->all();

        $total_price = 0;

        if (!empty($list)) {
            foreach ($list as &$item) {
                // 商品总数
                $lists['goodsTotalNumber'] += $item['number'];
                // 总价格
                $total_price += $item['total_price'];
                // 处理图片
                $item['goods']['thumb'] = ImageHelper::tomedia($item['goods']['thumb']);
                $item['specVal'] = str_replace('_', '/', $item['spec_val']);
                $goods_num[$item['goods_id']] += $item['number'];
            }
            $lists['goods'] = $list;
            $lists['goods_num'] = $goods_num;
            $lists['total_price'] = $total_price;
            // 计算运费
            $lists['freight'] = self::freight();

            $lists['pay_price'] = number_format($total_price + $lists['freight'], 2, '.', '');
        } else {
            $lists['goodsTotalNumber'] = 0;
            // 总价格
            $lists['total_price'] = 0;
            $lists['pay_price'] = $total_price;
            $lists['goods'] = [];
            // 计算运费
            $lists['freight'] = self::freight();
        }

        $store = Yii::$app->service->commonGlobalsService->getStoreDetail($store_id);
        $sendtime = $store['sendtime'];
        
        $lists['delivery_times'] = self::delivery_time($sendtime);

        return $lists;
    }

    // 获取配送范围内的时间
    public static function delivery_time($sendtime)
    {
        $times = explode(',', $sendtime);
        $time = [];
        $time[1] = $times;
        $day[1]  = '明天';
        // 今天的：
        foreach ($times as $key => $item) {
            list($start, $end) = explode('-', $item);
            $starttime = strtotime($start);
            $endtime = strtotime($end);
            
            $num = $starttime < time() ? time() : $starttime;
            if ($endtime > time()) {
                $time[0][] = $item;
                $day[0]='今天';
            }
        }

        return [$day,$time];
    }

    public static function clearAll($user_id)
    {
        $res = DdDiandiShopCart::deleteAll(['user_id' => $user_id]);

        return self::list($user_id);
    }

    public static function freight()
    {
        $store_id = Yii::$app->params['store_id'];
        $store = Yii::$app->service->commonGlobalsService->getStoreDetail($store_id);

        return  $store['shippingDees'] ? $store['shippingDees'] : 0;
    }
}
